package java_demos.java_basic.thread_demos;

import java.util.concurrent.*;

public class ThreadDemo01 {
    /*
    * 实现多线程有三种方法
    * 1.继承Thread，使用start()方法启动
    * 2.实现Runnable接口，传递Thread对象
    * 3.实现Callable接口，用Future进行接收
    * */
    static class MyThread01 extends Thread{
        @Override
        public void run() {
            System.out.println("MyThread01:"+"这是我创建线程重写的run()方法");
        }
    }
    static class Mythread02 implements Runnable{

        @Override
        public void run() {
            System.out.println("MyThread02:"+"这是我创建线程重写的run()方法");
        }
    }
    static class MyThread03 implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "MyThread03:这是一条来自实现了Callable接口的返回信息";
        }
    }
    public static void main(String[] args) {
        // 继承Thread的方式的多线程调用
        MyThread01 myThread01 = new MyThread01();
        myThread01.start();

        // 实现Runnale接口的多线程调用
        Mythread02 mythread02 = new Mythread02();
        Thread thread02 = new Thread(mythread02);
        thread02.start();

        // 实现Callable接口的多线程调用,先要创建一个线程池，再创建线程任务对象，传递给线程池，获取执行的结果
        ExecutorService excutor = Executors.newSingleThreadExecutor();
        MyThread03 task = new MyThread03();
        Future<String> future = excutor.submit(task);

        try {
            String message = future.get();
            System.out.println(message);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }finally{
            excutor.shutdown();
        }


    }


}
